import requests
import json
import logging
import falcon
import conf

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class VisionExtract(object):
    """
    This class constitutes of the functions needed to extract text from any format file using ocr_vision service
    """

    def __init__(self):
        self.convert_url = '{convert-url}'.format(**conf.OCR_VISION)
        self.header = {'Content-Type': "application/json"}

    def image_load(self, link: str):
        """
        Calls ocr-vision api and img_string receives image string list (base64 encoded)

        :param link: (str) resume link
        :return: output: (list) list of image strings (base64 encoded)
        """
        json_data = {"url": link}
        try:
            image_str = requests.request(
                "POST", self.convert_url, data=json.dumps(json_data), headers=self.header)
        except Exception as e:
            logger.error("Unable to convert document to image: " + str(e))
            raise falcon.HTTPInternalServerError(
                "Unable to convert document to image, (Please retry): " + str(e))
        if (image_str.status_code == 400):
            error = json.loads(image_str.text)
            logger.error("OCR Convert Error: " + error["title"])
            raise falcon.HTTPBadRequest("OCR Convert Error: " + error["title"])
        elif (image_str.status_code == 404):
            error = json.loads(image_str.text)
            logger.error("Link Not Found: " + error["title"])
            raise falcon.HTTPBadRequest("Link Not Found: " + error["title"])
        elif (image_str.status_code == 500):
            error = json.loads(image_str.text)
            logger.error("OCR Convert Error: " + error["title"])
            raise falcon.HTTPInternalServerError(
                "OCR Convert Error: " + error["title"])
        try:
            output = json.loads(image_str.text)
        except Exception as e:
            logger.error("OCR Convert Invalid Response: " + str(e))
            raise falcon.HTTPInternalServerError(
                "OCR Convert Invalid Response: " + str(e))
        logger.info('---- Images string received ----')
        return output['img_list']
